package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.heaven.entity.TeacherScore;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 教师评分dao
 * Created by wyh on 2015/3/26.
 */
@Repository
public class TeacherScoreDao extends BaseDao {

    /**
     * 保存评分
     * @param teacherScore 教师评分
     * @return int
     *
     * @author wyh
     * @since 2015-03-26
     */
    public int saveScore(TeacherScore teacherScore){
        String sql = "INSERT INTO t_teacher_score VALUES(NULL, :advice, :score, :courseId, :courseCode, :chapterId, :studentId, :teacherId, NOW())";

        SqlParameterSource sps = new BeanPropertySqlParameterSource(teacherScore);

        log.debug("返回 保存评分的结果");
        return namedParameterJdbcTemplate.update(sql, sps);
    }

    /**
     * 评分预览
     * @param groupId 群组ID
     * @param chapterId 章ID
     * @param studentId 学生ID
     * @return Map
     *
     * @author wyh
     * @since 2015-03-27
     */
    public Map<String, Object> getScore(long groupId, long chapterId, long studentId){
        String sql = "SELECT tiScore, sAdvice FROM t_teacher_score, t_course_group WHERE sCourseCode=sCode AND t_course_group.id=:groupId AND iStudentId=:studentId AND iChapterId=:chapterId";

        SqlParameterSource sps = new MapSqlParameterSource().addValue("groupId", groupId).addValue("studentId", studentId).addValue("chapterId", chapterId);

        try {
            log.debug("返回 评分预览");
            return namedParameterJdbcTemplate.queryForObject(sql, sps, new RowMapper<Map<String, Object>>() {
                @Override
                public Map<String, Object> mapRow(ResultSet resultSet, int i) throws SQLException {
                    Map<String, Object> result = new HashMap<>();
                    result.put("score", resultSet.getInt("tiScore"));
                    result.put("suggest", resultSet.getString("sAdvice"));
                    return result;
                }
            });
        } catch (EmptyResultDataAccessException ex){
            log.debug("查询评分为空");
            log.warn("查询的记录不存在");
            return null;
        }
    }
}
